package com.genentech.bioinformatics.mobi;
/*
 * Class by Jeff Milton, except where otherwise noted.
 */
import java.util.HashMap;
import java.util.Set;

import com.genentech.flexigraph.Grid;

public class GridIndex {
	private static Grid background = null;
	private static HashMap<String, Grid> grids = new HashMap<String, Grid>();
	private static HashMap<String, GANnotation> annotations = new HashMap<String, GANnotation>();
	private static HashMap<String, TermGraph> graphs = new HashMap<String, TermGraph>();

	public static void addGrid(String _key, Grid _g) {
		if (_key.equals("background"))
			background = _g;
		grids.put(_key, _g);
	}

	public static void addAnnotation(String key, GANnotation _annotation) {
		annotations.put(key, _annotation);
	}

	/**
	 * @param _key
	 * @return
	 */
	public static Grid getGrid(String _key) {
		return grids.get(_key);
	}

	public static Grid getGrid(float x, float y) {
		Set<String> st = grids.keySet();
		for (String sd : st) {
			if (sd.equals("background")) {
				continue;
			}
			Grid g = grids.get(sd);
			if (x > g.getXi() && x < (g.getXi() + g.getWidth())
					&& y > g.getYi() && (y < (g.getYi() + g.getHeight()))) {
				return g;
			}
		}

		// if none of the others are selected then move the background:
		Grid background = grids.get("background");
		if (x > background.getXi()
				&& x < (background.getXi() + background.getWidth())
				&& y > background.getYi()
				&& (y < (background.getYi() + background.getHeight()))) {
			return background;
		}
		return null;
	}

	/**
	 * get the term graph given an x and y screen value
	 * 
	 * @param x
	 * @param y
	 * @return
	 */
	public static TermGraph getTermGraph(float x, float y) {
		if (background == null)
			return null;

		Set<String> st = graphs.keySet();
		for (String sd : st) {
			if (sd.equals("background")) {
				continue;
			}
			TermGraph tg = graphs.get(sd);
			Grid g = tg.getGrid();
			int xi = background.X(g.getXi());
			int width = background.screenWidth(g.getWidth());
			int yi = background.Y(g.getYi());
			int height = background.screenHeight(g.getHeight());

			if (x > xi && x < (xi + width) && (y > (yi-height)) && (y < yi)) {
				return tg;
			}
		}
		return null;
	}

	public static GANnotation getAnnotation(float x, float y) {
		Set<String> st = annotations.keySet();
		for (String sd : st) {
			if (sd.equals("background")) {
				continue;
			}
			GANnotation gan = annotations.get(sd);
			if (x > gan.getX() && x < (gan.getX() + gan.getWidth())
					&& y > gan.getY() && (y < (gan.getY() + gan.getHeight()))) {
				return gan;
			}
		}
		return null;
	}

	/**
	 * Add the term graph
	 * 
	 * @param string
	 * @param value
	 */
	public static void addTermGraph(String string, TermGraph value) {
		graphs.put(string, value);

	}

}
